const http = require('http');

const sendJsonResponse = function (res, code, data, message) {
    res.writeHead(200, {'Content-Type': 'application/json; charset=UTF-8'});
    const responseData = {
        code: code,
        data: data,
        message: message
    }
    res.end(JSON.stringify(responseData));
}

// 3. 路由定义
const routes = {
    "/": (req, res) => {
        sendJsonResponse(res, 200, {
            message: "欢迎来到我的 Node.js 后端！",
            nodeId: process.version,
            timestamp: new Date().toISOString()
        }, "success");
    },
    '/users': (req, res) => {
        sendJsonResponse(res, 200, {
            users: [
                {id: 1, name: "Alice"},
                {id: 2, name: "Bob"}
            ],
            total: 2,
        }, "获取用户列表")
    },
    '/products': (req, res) => {
        sendJsonResponse(res, 200, {
            products: [
                {id: 1, name: "Laptop", price: 999},
                {id: 2, name: "Mouse", price: 25}
            ],
            total: 2
        }, "获取产品列表成功")
    },
    '/status': (req, res) => {
        sendJsonResponse(res, 200, {
            status: "running",
            uptime: process.uptime()
        }, "状态获取成功");
    },
    '/error': (req, res) => {
        sendJsonResponse(res, 500, null, "这是一个模拟的错误消息");
    }
}

// 创建一个 http 服务器
const server = http.createServer((req, res) => {
    // 从路由中查找对应的处理函数
    const handler = routes[req.url];

    if (handler) {
        // 如果找到就执行他
        handler(req, res);
    } else {
        // 如果没有找到 返回404
        res.writeHead(404, {'Content-Type': 'application/json; charset=UTF-8'});
        const errorResponse = {
            code: 404,
            data: null,
            message: "Not Found",
        };
        res.end(JSON.stringify(errorResponse));
    }
});

// 让服务器监听 3000 端口
const PORT = 3000
server.listen(PORT, () => {
    console.log(`服务器已启动，访问 http://localhost:${PORT}`);
    console.log('可用路由:');
    Object.keys(routes).forEach(route => {
        console.log(`  GET ${route}`);
    });
    console.log('  404 其他未定义路径');
});

// 如何运行:
// 1. 将代码保存为 server.js
// 2. 在终端执行: node server.js
// 3. 打开浏览器访问不同的 URL 查看效果
// 4. 要添加新路由，只需在 routes 对象中添加新的键值对即可